#include "clientwidget.h"
#include "ui_clientwidget.h"
#include <QMessageBox>
ClientWidget::ClientWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ClientWidget)
{
    ui->setupUi(this);
    //分配空间，指定父对象
    m_tcpSocket = new QTcpSocket(this);
    setWindowTitle("Client");
    ui->textEditWrite->clear();
    connect(m_tcpSocket,&QTcpSocket::connected,
            [=](){
        ui->textEditRead->setText("成功建立连接");
    });
    connect(m_tcpSocket,&QTcpSocket::readyRead,[=](){
        //获取内容追加到编辑区
        QByteArray array = m_tcpSocket->readAll();
        array.insert(0,"Server: ");
        ui->textEditRead->append(array);
    });


}

ClientWidget::~ClientWidget()
{
    delete ui;
}

void ClientWidget::on_pushButtonConnect_clicked()
{
    //获取服务器Ip 和端口
    QString ip = ui->lineEditIP->text();
    qint16 port =ui->lineEditPort->text().toInt();
    //主动和服务器建立连接
    m_tcpSocket->connectToHost(QHostAddress(ip), port);
}

void ClientWidget::on_pushButtonSend_clicked()
{
    //获取编辑区内容
    QString str = ui->textEditWrite->toPlainText();
    if(str.isEmpty())
    {
        QMessageBox mybtn(QMessageBox::Warning,QString("Info"),QString("Send Context is Empty"));
        mybtn.setStandardButtons(QMessageBox::Yes);
        mybtn.setButtonText(QMessageBox::Yes,QString("OK"));
        if(QMessageBox::Yes == mybtn.exec())
        {
            //判断

        }
        return;

    }


    ui->textEditWrite->clear();
    m_tcpSocket->write(str.toUtf8().data());
}

void ClientWidget::on_pushButtonClose_clicked()
{
    //主动和对方端口连接；
    m_tcpSocket->disconnectFromHost();
    m_tcpSocket->close();
    ui->textEditWrite->clear();
}
